<?php

namespace App\Models;

use Dcat\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;

class FhCategory extends Model
{
	use ModelTree;
    protected $table = 'fh_category';
    protected $parentColumn = 'pid';
    protected $titleColumn = 'c_name';
    protected $orderColumn = 'sort';

    public static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
           
            if($model->pid==0){
                if(strpos($model->c_url, "/project-category/") === false){
                    $url = str_replace(" ","-",$model->c_url);
                    $model->c_url = "/project-category/".$model->c_url;
                }
            }else{
                $url = $model->where('id',$model->pid)->value('c_url');
                if(strpos($model->c_url, $url) === false){
                    $model->c_url = $url.'/'.$model->c_url;
                }
            }
     
        });
    }

    public function getCate(){
        $data = $this->where('show',1)->select('id','c_name','c_url','pid','sort')->get()->toArray();
        
        $tree = $this->getTree($data);
        $this->sortArray($tree);
        return $tree;
    }
    
    protected function getTree($data,$parent = 0){
        $tree = [];
        $count = 0;
        foreach($data as $v){
            if($v['pid']==$parent){
                $tree[$count] = $v;
                $tree[$count]['sub']= $this->getTree($data,$v['id']);
                $count++;
            }
        }
        
        return $tree;
    }
    protected function sortArray(&$array){
        usort($array, function($a, $b) {
            return   $b['sort'] - $a['sort'];
        });
    
        foreach ($array as &$item) {
            if (isset($item['sub'])) {
                $this->sortArray($item['sub']);
            }
        }
    }
}
